package com.z.util.convert;

import java.util.LinkedList;

import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

public class ConvertManager {
	private static ConvertManager convertManager;
	public static ConvertManager getInstance(){
		if(convertManager==null){
			convertManager=new ConvertManager();
			convertManager.start();
		}
		return convertManager;
	}
	
	private final PoolWorker thread = new PoolWorker();// 用数组实现线程池
	private final LinkedList<Runnable> queue = new LinkedList<Runnable>();// 任务队列
	private OfficeManager officeManager = null;
	public OfficeManager getOfficeManager() {
		return officeManager;
	}

	private boolean running=false;
	public void start(){
		running=true;
		officeManager = new DefaultOfficeManagerConfiguration().buildOfficeManager();
	    officeManager.start();
        thread.start();
	}
	
	public void stop(){
		if(running){
			running=false;
			officeManager.stop();
		}
	}

    public void execute(Runnable r) {// 执行任务 
        synchronized (queue) {
            queue.addLast(r);
            queue.notify();
        }
    }
    
	private class PoolWorker extends Thread {// 工作线程类
        public void run() {
            Runnable r;
            while (true) {
                synchronized (queue) {
                    while (queue.isEmpty()) {// 如果任务队列中没有任务，等待
                        try {
                            queue.wait();
                        } catch (InterruptedException ignored) {
                        }
                    }
                    r = (Runnable) queue.removeFirst();// 有任务时，取出任务
                }
                try {
                    r.run();// 执行任务
                } catch (RuntimeException e) {
                    // You might want to log something here
                }
            }
        }
    }
}
